import os
import sys
import warnings
import pandas as pd

sys.path.append('..')
warnings.filterwarnings('ignore')

from tools.setting import DATA_DIR
from API.currency import get_currency_historical_price, get_currency_latest_price
from API.okex import get_usdtusd_premium_okex, get_usdtcny_premium_okex, get_usdtcny_orderbook_okex
from API.btc126 import get_btc126_usdtcny_premium
from tools.logger import logger

PREMIUM_DATA_DIR = os.path.join(DATA_DIR, 'usdt_premium')
os.makedirs(PREMIUM_DATA_DIR, exist_ok=True)


def update_usdcnh():
    # 从新浪获取离岸人民币汇率的历史数据，直接获取全部数据，每日更新
    logger.info('更新离岸人民币汇率')
    file_name = os.path.join(PREMIUM_DATA_DIR, 'usdcnh_exchange_rate.csv')
    df = get_currency_historical_price(symbol='USDCNH')
    df.to_csv(file_name, index=False)


def update_usdtusd_premium_okex():
    # 从okex获取不同频率的usdtusd溢价数据，每日更新
    logger.info('更新不同频率的usdtusd溢价数据')
    for frequency in ['5m', '1h', '1d']:
        update = get_usdtusd_premium_okex(frequnecy=frequency)
        file_name = os.path.join(PREMIUM_DATA_DIR, f'usdtusd_premium_{frequency}_okex.csv')
        if os.path.exists(file_name):
            historical_df = pd.read_csv(file_name)
            if max(historical_df['datetime']) < max(update['datetime']):
                df = pd.concat([historical_df, update], axis=0, ignore_index=True)
                df.drop_duplicates(subset=['datetime'], keep='first', inplace=True)
                df.to_csv(file_name, index=False)
        else:
            update.to_csv(file_name, index=False)


def update_usdtcny_premium_and_orderbook_okex():
    # 从okex获取usdt对cny溢价数据和盘口信息，每小时更新
    logger.info('更新usdt对cny溢价数据和盘口信息')
    file_name = os.path.join(PREMIUM_DATA_DIR, f'usdtcny_premium_okex.csv')
    orderbook_file_name = os.path.join(PREMIUM_DATA_DIR, f'usdtcny_orderbook_okex.csv')

    last_usdcnh = get_currency_latest_price(symbol='USDCNH')
    premium = get_usdtcny_premium_okex()
    premium['usdcnh'] = last_usdcnh
    premium['premium'] = (premium['usdtcny'] - last_usdcnh) / last_usdcnh
    if os.path.exists(file_name):
        historical_premium = pd.read_csv(file_name)
        df = pd.concat([historical_premium, premium], axis=0, ignore_index=True)
        df.drop_duplicates(subset=['datetime'], keep='first', inplace=True)
        df.to_csv(file_name, index=False)
    else:
        premium.to_csv(file_name, index=False)

    orderbook = get_usdtcny_orderbook_okex()
    if os.path.exists(orderbook_file_name):
        historical_orderbook = pd.read_csv(orderbook_file_name)
        df_ob = pd.concat([historical_orderbook, orderbook], axis=0, ignore_index=True)
        df_ob.drop_duplicates(subset=['datetime', 'id'], keep='first', inplace=True)
        df_ob.to_csv(orderbook_file_name, index=False)
    else:
        orderbook.to_csv(file_name, index=False)


def update_usdtcny_premium_btc126():
    # 从btc126获取usdt兑cny溢价，每日更新
    logger.info('更新btc126上的usdt兑cny溢价')
    file_name = os.path.join(PREMIUM_DATA_DIR, 'usdtcny_premium_btc126.csv')
    update = get_btc126_usdtcny_premium()
    if os.path.exists(file_name):
        historical_df = pd.read_csv(file_name)
        df = pd.concat([historical_df, update], axis=0, ignore_index=True)
        df.drop_duplicates(subset=['atime'], keep='first', inplace=True)
        df.to_csv(file_name, index=False)
    else:
        update.to_csv(file_name, index=False)


if __name__ == '__main__':
    update_usdcnh()
    update_usdtusd_premium_okex()
    update_usdtcny_premium_btc126()
    # update_usdtcny_premium_and_orderbook_okex()